package com.ruoyi.web.controller.estate;

import java.util.List;
import java.util.Map;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.estate.Resident;
import com.ruoyi.system.service.estate.IResidentService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.Convert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 住户管理Controller
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/estate/resident")
public class ResidentController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(ResidentController.class);

    @Autowired
    private IResidentService residentService;

    @Autowired
    private ISysUserService userService;

    /**
     * 查询住户列表
     */
    @PreAuthorize("@ss.hasPermi('estate:resident:list')")
    @GetMapping("/list")
    public TableDataInfo list(Resident resident)
    {
        startPage();
        List<Resident> list = residentService.selectResidentList(resident);
        return getDataTable(list);
    }

    /**
     * 导出住户列表
     */
    @PreAuthorize("@ss.hasPermi('estate:resident:export')")
    @Log(title = "住户管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Resident resident)
    {
        List<Resident> list = residentService.selectResidentList(resident);
        ExcelUtil<Resident> util = new ExcelUtil<Resident>(Resident.class);
        return util.exportExcel(list, "住户数据");
    }

    /**
     * 获取住户详细信息
     */
    @PreAuthorize("@ss.hasPermi('estate:resident:query')")
    @GetMapping(value = "/{residentId}")
    public AjaxResult getInfo(@PathVariable("residentId") Long residentId)
    {
        return AjaxResult.success(residentService.selectResidentById(residentId));
    }

    /**
     * 新增住户
     */
    @PreAuthorize("@ss.hasPermi('estate:resident:add')")
    @Log(title = "住户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Resident resident)
    {
        return toAjax(residentService.insertResident(resident));
    }

    /**
     * 修改住户
     */
    @PreAuthorize("@ss.hasPermi('estate:resident:edit')")
    @Log(title = "住户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Resident resident)
    {
        return toAjax(residentService.updateResident(resident));
    }

    /**
     * 删除住户
     */
    @PreAuthorize("@ss.hasPermi('estate:resident:remove')")
    @Log(title = "住户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{residentIds}")
    public AjaxResult remove(@PathVariable Long[] residentIds)
    {
        return toAjax(residentService.deleteResidentByIds(residentIds));
    }

    /**
     * 关联住户和用户
     */
    @PostMapping("/linkUser")
    public AjaxResult linkUser(@RequestBody Map<String, Object> params) {
        log.info("接收到关联用户请求: {}", params);
        
        try {
            // 实现关联逻辑
            // 如果是关联已有用户
            if ("existing".equals(params.get("linkType"))) {
                Long residentId = Convert.toLong(params.get("residentId"));
                Long userId = Convert.toLong(params.get("userId"));
                log.info("关联已有用户: residentId={}, userId={}", residentId, userId);
                
                // 调用service方法关联住户和用户
                return toAjax(residentService.linkResidentUser(residentId, userId));
            } 
            // 如果是创建新用户并关联
            else if ("new".equals(params.get("linkType"))) {
                log.info("创建新用户并关联");
                
                // 创建新用户
                SysUser user = new SysUser();
                user.setUserName((String) params.get("userName"));
                user.setNickName((String) params.get("nickName"));
                user.setPassword(SecurityUtils.encryptPassword((String) params.get("password")));
                
                // 调用service方法创建用户并关联
                return toAjax(userService.insertUserAndLinkResident(user, Convert.toLong(params.get("residentId"))));
            }
            
            return AjaxResult.error("关联类型不正确");
        } catch (Exception e) {
            log.error("关联用户失败", e);
            return AjaxResult.error("关联用户失败: " + e.getMessage());
        }
    }

    /**
     * 解除住户和用户的关联
     */
    @DeleteMapping("/unlinkUser/{residentId}")
    public AjaxResult unlinkUser(@PathVariable Long residentId) {
        return toAjax(residentService.unlinkResidentUser(residentId));
    }

    /**
     * 获取住户关联的用户信息
     */
    @GetMapping("/user/{residentId}")
    public AjaxResult getResidentUser(@PathVariable Long residentId) {
        return AjaxResult.success(userService.selectUserByResidentId(residentId));
    }
} 